package com.base.thread.demo_32;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Tmall {

	private int count;
	
	//最多可生产10个
	public final int MAX_COUNT = 10;
	
	private Lock lock = new ReentrantLock();
	
	Condition p =  lock.newCondition();
	Condition t =  lock.newCondition();
	
	
	public  void push() {
		lock.lock();
		while (count >= MAX_COUNT) {
			System.out.println(Thread.currentThread().getName() + " 库存数量达到上限，生产者停止生产。");
			try {
				p.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		count ++ ;
		System.out.println(Thread.currentThread().getName() + " 生产者生产，当前库存为：" + count);
		//notifyAll();//唤醒所有消费者
		t.signal();//唤醒消费者
//		t.signalAll();//唤醒消费者
		lock.unlock();
	}
	
	public  void take() {
		lock.lock();
		while (count <= 0) {
			System.out.println(Thread.currentThread().getName() + " 库存数量为零，消费者等待。");
			try {
				t.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		count -- ;
		System.out.println(Thread.currentThread().getName() + " 消费者消费，当前库存为：" + count);
		p.signal();
		lock.unlock();
	}
	
	
}
